
#include "CxRevThread.h"

using namespace DataRevPart;

CxRevThread::CxRevThread(size_t number,const string &portname,UINT portno,_ConnectFunc _func):
						CxThread(),
						m_number(number),
                        m_isconnect(false),
						m_buffer(32),
						m_phandle(new CxDataHandle_W),
                        m_spin(true),
                        m_ipaddr(portname),
                        m_portno(portno),
                        m_client(NULL)
{
	OpenPort(portname,portno);
	//m_client.OpenPort(porname,portno,boost::bind(&CxRevThread::ConnectedFunc,this,_1));
	m_state=THREAD_SUSPEND;
}

CxRevThread::CxRevThread(size_t number):
			m_number(number),
			m_isconnect(false),
			m_buffer(32),
			m_phandle(new CxDataHandle_W),
			m_spin(true),
			m_ipaddr(""),
            m_portno(-1),
            m_client(NULL)
{
	m_state=THREAD_SUSPEND;
}

CxRevThread::~CxRevThread()
{
	Close();
	if(m_phandle!=NULL)delete m_phandle;
}

inline	void	CxRevThread::Start()
{
	m_state=THREAD_RUNNING;
}

inline	void	CxRevThread::Close()
{
	m_spin=false;
	m_thread.interrupt();
	m_thread.join();
	m_state=THREAD_CLOSE;
}

void		CxRevThread::RunFunc()
{	
	cout<<"Rev thread id "<<boost::this_thread::get_id()<<endl;
	try
	{
		while(m_spin)
		{	
			//Mian loop to handle the data
            boost::this_thread::sleep(boost::posix_time::milliseconds(30));
            if(m_isconnect)
               m_phandle->CombineMat(m_client,&m_buffer);
		}
	}
	catch(boost::thread_interrupted &)
	{

	}
	catch(const boost::system::system_error &e)
	{
        CX_ERR_MESSAGE(e.what())
	}
}

bool		CxRevThread::OpenPort(const string &portname,UINT  portno,_ConnectFunc _Func)
{
    if(m_client!=NULL)     
        delete m_client;


    m_ipaddr=portname;
    m_portno=portno;

	m_client=new CxTcpClient;
	m_client->AddConnectedFunc(_Func);
	m_client->AddBreakFunc(boost::bind(&CxRevThread::BreakFunc,this));

    cout<<"Now is connect "<<portname<<" portno is "<<portno<<endl;
    m_client->OpenPort(portname,portno,boost::bind(&CxRevThread::ConnectedFunc,this,_1));

    return true;
}

void		CxRevThread::ConnectedFunc(bool	isconnect)
{
	if(isconnect)
	{
        cout<<"Connected...."<<endl;

        m_phandle->ConnectedSlot(m_client,m_number);
        m_isconnect=true;
	}
	else 
	{
        delete m_client;
        m_client=NULL;
        m_isconnect=false;
		cout<<"Not connected....."<<endl;

//        boost::this_thread::sleep(boost::posix_time::seconds(2));
//        m_client.OpenPort(m_ipaddr,m_portno,boost::bind(&CxRevThread::ConnectedFunc,this,_1));
	}
}


//Connect break handle
void	CxRevThread::BreakFunc()
{
    m_isconnect=false;	
    cout<<"Client have been break....\nThis is CxRevThread...."<<endl;
}
